package com.keqiang.filepicker

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import java.util.*


/**
 * 文件选择主界面
 *
 * @author Created by wanggaowan on 2022/5/18 14:00
 */
internal class FilePickerActivityWrapper : AppCompatActivity() {

    private var mUUID: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val view = View(this)
        setContentView(view)

        mUUID = intent.getStringExtra(UID)
        val intent = Intent(this, FilePickerActivity::class.java)
        intent.putExtras(getIntent())
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            finish()
            val callback = map[mUUID]
            callback?.let {
                if (result == null || result.resultCode != Activity.RESULT_OK || result.data == null) {
                    it.onCallback(null)
                } else {
                    val data =
                        result.data?.getParcelableArrayListExtra<Uri>(FilePickerActivity.CHOSEN_DATA_LIST)
                    it.onCallback(data)
                }
            }
        }.launch(intent)
    }

    companion object {
        /**
         * 将扫码回调与Activity绑定
         */
        private val map: HashMap<String, FileChosenCallback> = HashMap()

        /**
         * 当前Activity的唯一标识
         */
        private const val UID = "uuid"

        fun start(context: Context, params: Intent, fileChosenCallback: FileChosenCallback) {
            val uuid = UUID.randomUUID().toString()
            map[uuid] = fileChosenCallback
            if (context is FragmentActivity) {
                context.lifecycle.addObserver(LifecycleEventObserver { _, event: Lifecycle.Event ->
                    if (event == Lifecycle.Event.ON_DESTROY) {
                        map.remove(uuid)
                    }
                })
            }

            val intent = Intent(context, FilePickerActivityWrapper::class.java)
            intent.putExtras(params)
            intent.putExtra(UID, uuid)
            context.startActivity(intent)
        }
    }
}